package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWoker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @Autowired
    private RedisIdWoker redisIdWoker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redisClient;

    @Override
    public Result seckillVoucher(Long voucherId) {
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        LocalDateTime now = LocalDateTime.now();
        //  判断是否在抢购时间内
        if (seckillVoucher.getBeginTime().isAfter(now)) {
            return Result.fail("抢购失败, 秒杀未开始");
        }
        if (seckillVoucher.getEndTime().isBefore(now)) {
            return Result.fail("抢购失败, 秒杀已结束");
        }
        //  判断是否还有库存
        Integer stock = seckillVoucher.getStock();
        if (stock < 1) {
            return Result.fail("抢购失败, 库存不足");
        }

        Long id = UserHolder.getUser().getId();
        RLock lock = redisClient.getLock("lock:order:" + id);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            return Result.fail("已达到购买上限");
        }

        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.creatOrder(voucherId);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    public Result creatOrder(Long voucherId) {
        //  获取用户已购买数量
        Long id = UserHolder.getUser().getId();
        VoucherOrder voucherOrder = new VoucherOrder();
        int count = voucherOrderService.query().eq("user_id", id).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("抢购失败, 已达到购买上限");
        }

        //  减少库存
        boolean isUpdate = seckillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherId).gt("stock", 0).update();

        if (!isUpdate) {
            return Result.fail("抢购失败, 库存不足");
        }

        // 创建订单
        voucherOrder.setId(redisIdWoker.nextId("order"));
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);

        //  存入订单
        save(voucherOrder);
        return Result.ok(voucherOrder.getId());

    }
}
